#include "my_account.hpp"
#include "pjsip_manager.hpp"
#include <regex>

using namespace pj;

MyAccount::MyAccount(AccountConfig config)
{
    _config = config;
}

void MyAccount::onIncomingCall(OnIncomingCallParam &prm)
{
    int callId = prm.callId;

    string value = prm.rdata.wholeMsg;

    string xid = "";

    vector<string> lines;
    stringsplit(value, "\n", lines);

    for (auto s : lines)
    {
        string::size_type idx = s.find("XID");
        string::size_type idx2 = s.find("From:");
        if (idx != string::npos)
        {
            vector<string> components;
            stringsplit(s, ":", components);
            if (components.size() > 1)
            {
                string find1 = "\r";
                string find2 = " ";
                string find3 = "qhend";
                xid = components[components.size()-1];
                xid = xid.replace(xid.find(find1), find1.length(), "");
                xid = xid.replace(xid.find(find2), find2.length(), "");
                xid = xid.replace(xid.find(find3), find3.length(), "");
            }

            break;
        }
        else if (idx2 != string::npos)
        {
            cout << "match2 " << s << endl;
            string find1 = "\r";
            s = s.replace(s.find(find1), find1.length(), "");
            string result = midstr(s, "sip:", "qhend");
            cout << "match3 " << result << endl;
            if (result.length() > 1)
            {
                xid = result;
                break;
            }
        }
    }

    PJSUAManager::getInstace()->onImcomingCall(callId, xid);
}

void MyAccount::stringsplit(const string &str, const string &splits, vector<string> &res)
{
    if (str == "")
        return;
    string strs = str + splits;
    size_t pos = strs.find(splits);
    auto step = splits.size();

    while (pos != strs.npos)
    {
        string temp = strs.substr(0, pos);
        res.push_back(temp);
        strs = strs.substr(pos + step, strs.size());
        pos = strs.find(splits);
    }
}

string MyAccount::midstr(string oldstr, string startstr, string endstr)
{
    string re = ".*?" + startstr + "(.*?)" + endstr + ".*?";
    regex pattern(re);
    smatch results;
    if (regex_match(oldstr, results, pattern))
        return results[1];
    else
        cout << "match failed: " << oldstr << endl;
    return "";
}